package com.renwei.yunlong.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.renwei.yunlong.R;
import com.renwei.yunlong.http.DownloadUtils;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.StringUtils;
import com.tencent.smtt.sdk.TbsReaderView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.PermissionUtil;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import github.opensource.dialog.BeToastUtil;

/**
 * Project :  yunaandroid.
 * Package name: com.renwei.yunlong.activity
 * Created by :  Benjamin.
 * Created time: 2017/11/24 10:58
 * Changed by :  Benjamin.
 * Changed time: 2017/11/24 10:58
 * Class description:
 */

public class FileDisplayActivity extends AppCompatActivity implements DownloadUtils.DownloadLisener, RationaleListener, PermissionListener, TbsReaderView.ReaderCallback {
    private final String TAG = "FileDisplayActivity";
    @Bind(R.id.tv_information)
    TextView tvInformation;
    @Bind(R.id.tbsParent)
    LinearLayout tbsParent;
    private TbsReaderView mTbsReaderView;
    String path;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_display);
        ButterKnife.bind(this);
        tbsParent = (LinearLayout) findViewById(R.id.tbsParent);
        mTbsReaderView = new TbsReaderView(this, FileDisplayActivity.this);
        tbsParent.addView(mTbsReaderView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        path = getIntent().getStringExtra("path");
        PermissionUtil.checkOnePermission(this, 999, FileDisplayActivity.this, FileDisplayActivity.this, Permission.STORAGE);
    }


    /**
     * 显示文件，当文件路径中用Htttp开头的时候，就先去下载文件
     * 下载文件下载成功之后在吧文件路径去显示文件
     *
     * @param path
     */
    public void displayFile(String path) {
        if (path != null) {
            String bsReaderTemp = this.getCacheDir() + "/cacheFile/";
            if (path.startsWith("http")) {
                File tempFile = new File(bsReaderTemp);
                if (!tempFile.exists()) {
                    tempFile.mkdir();
                }
                DownloadUtils.getInstance()
                        .setDownloadLisener(this)
                        .showDownLoadDialog(this, true)
                        .downloadFile(path, bsReaderTemp);

            } else {
                final File file = new File(path);
                if (file.exists()) {
                    //显示文件
                    final Bundle bundle = new Bundle();
                    bundle.putString("filePath", path);
                    bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
                    String pathFormat = parseFormat(path);
                    boolean result = mTbsReaderView.preOpen(pathFormat, false);
                    LogUtil.e("tbs------文件名称" + StringUtils.value(file.getName()) + "文件格式:" + pathFormat + "预加载结果" + result);
                    if (result) {
                        tvInformation.setVisibility(View.GONE);
                        mTbsReaderView.openFile(bundle);
                    } else {
                        tvInformation.setVisibility(View.VISIBLE);
                        tvInformation.setText("不支持的文件格式");
                    }

                } else {
                    BeToastUtil.get().showCenterInfoMsg(this, "文件不存在");
                }
            }
        } else {
            BeToastUtil.get().showCenterInfoMsg(this, "路径错误");
        }
    }

    //获取文件的格式判断文件是否支持 这里文件是不需要带.的 ******
    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    //这个地方需要请求权限 权限请求处理成功走onSuccess方法
    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
        AndPermission.rationaleDialog(this, rationale).show();
    }

    @Override //权限获取成功
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        if (AndPermission.hasPermission(this, grantPermissions)) {
            // 第一种：用默认的提示语。
            String temp = path;
            displayFile(path);
        } else {
            LogUtil.e(TAG + "没有权限");
        }

    }


    @Override //权限获取失败，弹窗提示重新尝试
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, PermissionUtil.SETTING_CODE).show();
        }
    }

    @Override
    public void onStartedDown() {
        LogUtil.e(TAG + "开始下载了");
    }

    @Override
    public void onDownError(Throwable ex, boolean isOnCallback) {
        LogUtil.e(TAG + "下载失败了" + ex.getMessage());
    }

    @Override
    public void onDownFinished(File result) {
        LogUtil.e(TAG + "下载成功了");
        if (result.exists()) {
            displayFile(result.getPath());
        } else {
            LogUtil.e(TAG + "文件不存在");
        }
    }


    /**
     * 退出的时候记得销毁以及移除tbsview 释放资源
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTbsReaderView.onStop();
        tbsParent.removeView(mTbsReaderView);
    }

    public static void openActivity(Context context, String path) {
        Intent intent = new Intent(context, FileDisplayActivity.class);
        intent.putExtra("path", path);
        context.startActivity(intent);
    }

    @Override
    public void onCallBackAction(Integer integer, Object o, Object o1) {
        LogUtil.e(String.valueOf(integer));
    }

}
